/**
 * YOLO API统一客户端
 * 提供统一的YOLO检测API调用接口
 */

import config, { buildUrls } from '../config/index.js'

class YOLOApiClient {
  constructor() {
    this.apiPrefix = '/api/yolo-detection';
  }

  /**
   * 获取完整的API URL
   */
  getApiUrl(endpoint) {
    // YOLO服务使用独立的端口8099
    const baseUrl = config.development ? 'http://127.0.0.1:8099' : 'http://8.136.52.147:8099';
    return `${baseUrl}${this.apiPrefix}${endpoint}`;
  }

  /**
   * 发送HTTP请求
   */
  async request(url, options = {}) {
    try {
      const response = await fetch(url, {
        headers: {
          'Content-Type': 'application/json',
          ...options.headers
        },
        ...options
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const result = await response.json();
      
      if (result.code !== 200) {
        throw new Error(result.message || 'API请求失败');
      }

      return result.data;
    } catch (error) {
      console.error('YOLO API请求失败:', error);
      throw error;
    }
  }

  /**
   * 获取模型信息
   */
  async getModelInfo() {
    return await this.request(this.getApiUrl('/model-info'));
  }

  /**
   * 检测图像中的目标
   */
  async detectObjects(imageFile, confidenceThreshold = null) {
    const formData = new FormData();
    formData.append('image', imageFile);
    
    // 如果提供了置信度阈值，添加到请求中
    if (confidenceThreshold !== null) {
      formData.append('confidence_threshold', confidenceThreshold.toString());
      console.log(`🔧 添加置信度阈值到FormData: ${confidenceThreshold}`);
    }

    try {
      const response = await fetch(this.getApiUrl('/detect-objects'), {
        method: 'POST',
        body: formData
      });

      if (!response.ok) {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`);
      }

      const result = await response.json();
      
      if (result.code !== 200) {
        throw new Error(result.message || '目标检测失败');
      }

      // 返回完整的data对象，包含objects数组
      return result.data;
    } catch (error) {
      console.error('YOLO目标检测失败:', error);
      throw error;
    }
  }

  /**
   * 获取检测统计信息
   */
  async getDetectionStats() {
    return await this.request(this.getApiUrl('/detection-stats'));
  }

  /**
   * 切换服务状态
   */
  async toggleService(enabled) {
    return await this.request(this.getApiUrl('/toggle-service'), {
      method: 'POST',
      body: JSON.stringify({ enabled })
    });
  }

  /**
   * 获取服务状态
   */
  async getServiceStatus() {
    return await this.request(this.getApiUrl('/status'));
  }

  /**
   * 检查服务是否可用
   */
  async checkServiceHealth() {
    try {
      await this.getModelInfo();
      return true;
    } catch (error) {
      console.warn('YOLO服务健康检查失败:', error);
      return false;
    }
  }
}

// 创建单例实例
const yoloApiClient = new YOLOApiClient();

export default yoloApiClient;
